package yuyicman.effects 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.filters.GlowFilter;
	import flash.geom.Point;
	import yuyicman.core.IDestroy;
	import yuyicman.core.DestroyManager;
	import yuyicman.debug.Debugger;
	
	/**
	 * ...
	 * @author Yuyic.
	 */
	public class LiquidFlow extends Bitmap implements IDestroy
	{
		
		private var _target:DisplayObject;
		private var _bitmapData:BitmapData;
		private var _point:Point;
		private var _color:uint;
		private var _argb:uint;
		
		private var _blurGlow:GlowFilter;
		private var _strokeGlow:GlowFilter;
		
		public function LiquidFlow(target:DisplayObject,width:int,height:int,color:uint) 
		{
			_target = target;
			_color = color;
			_argb = color + 0xFF000000;
			_bitmapData = new BitmapData(width,height,true,0);
			super( _bitmapData );
			init();
		}
		
		private function init():void {
			
			_point = new Point;
			
			_blurGlow = new GlowFilter();
			_blurGlow.color = _color;
			_blurGlow.blurX = 60;
			_blurGlow.blurY = 60;
			_blurGlow.strength = 2;
			_blurGlow.quality = 1;
			
			_strokeGlow = new GlowFilter();
			_strokeGlow.color = _color;
			_strokeGlow.blurX = 8;
			_strokeGlow.blurY = 8;
			_strokeGlow.strength = 2;
			_strokeGlow.quality = 2;
			
			_target.filters = [ _blurGlow ];
			filters = [ _strokeGlow ];
			
			_target.x = x;
			_target.y = y;
			_target.visible = false;
			
			startRender();	
			
			
		}
		
		public function quality( quality:int ):void {
			
			if ( quality == 1 ) {
				_blurGlow.blurX = 20;
				_blurGlow.blurY = 20;
				_blurGlow.strength = 2;
				_strokeGlow.strength = 4;
			}
			else if ( quality == 2 ) {
				_blurGlow.blurX = 40;
				_blurGlow.blurY = 40;
				_blurGlow.strength = 3;
				_strokeGlow.strength = 7;
			}
			else if ( quality == 3 ) {
				_blurGlow.blurX = 60;
				_blurGlow.blurY = 60;
				_blurGlow.strength = 4;
				_strokeGlow.strength = 10;
			}
			_target.filters = [ _blurGlow ];
			filters = [ _strokeGlow ];
			
		}
		
		private function render(e:Event):void {
			
			_bitmapData.fillRect( _bitmapData.rect, 0);
			_bitmapData.draw(_target);
			_bitmapData.threshold(_bitmapData, _bitmapData.rect, _point, "!=", _argb, 0);
		}
		
		public function startRender():void {
			addEventListener(Event.ENTER_FRAME, render);
		}
		
		public function stopRender():void {
			removeEventListener(Event.ENTER_FRAME, render);
		}
		
		public function destroy():void {
			
			stopRender();
			
			_bitmapData.dispose();
			_bitmapData = null;
			
			_target.filters = [];
			filters = [];
			
			_strokeGlow = null;
			_blurGlow = null;
			
			_target = null;
			
			if (parent) {
				parent.removeChild(this);
			}
			
			dispatchEvent(new Event(DestroyManager.DESTROY));
		}
		
	}

}